<?php

class CustomerController extends UserController
{

    public $type          = Users::TYPE_CUSTOMER;
    public $customerModel = NULL;
    public $biz_id        = NULL;
    public $staff_id      = NULL;

    protected function criteria()
    {
        $ret = new CDbCriteria();
        if (isset($_GET['key']))
        {
            $arr_keys = explode(' ', $_GET['key']);
            foreach ($arr_keys as $key)
            {
                $ret->with = array('user');
                $ret->compare('user.lastname', $key, TRUE, 'OR');
                $ret->compare('user.firstname', $key, TRUE, 'OR');
                $ret->compare('user.country', $key, TRUE, 'OR');
                $ret->compare('user.address', $key, TRUE, 'OR');
                $ret->compare('user.home_phone', $key, TRUE, 'OR');
                $ret->compare('user.city', $key, TRUE, 'OR');
                $ret->compare('user.mobile_phone', $key, TRUE, 'OR');
                $ret->compare('user.email', $key, true, 'OR');
            }
        }

        return $ret;
    }

    public function actionIndex()
    {
        $this->checkAccess();
        $this->search = true;

        $criteria = $this->criteria();
        //$criteria->order = 'user_id DESC';

        if ($this->isAdmin)
        {
            if (isset($_GET['business']))
            {
                //set ukey business
                $criteria->compare('biz_id', Users::getIdByUkey($_GET['business']));

                $this->filterBusiness = $_GET['business'];
            }
        }

        if ($this->isBussiness)
        {
            //Nếu là root Merchant thì show tất cả staff thuộc các chi nhánh của merchant đó
            if (isset($_GET['business']) && $_GET['business'] != 0)
            {
                if (!$this->isBranch)
                {
                    $biz_id              = (int) $_GET['business'];
                    $branch_ids          = Merchant::getAllBranchByBusiness(Yii::app()->user->id);
                    if (in_array($biz_id, $branch_ids))
                        $criteria->compare('biz_id', $biz_id);
                    else
                        $criteria->condition = "1=0";
                }
                else
                {
                    $user                = Yii::app()->user->getCurrentUser();
                    $branch_ids          = Merchant::getAllBranchByBusiness($user->author->id);
                    $biz_id              = (int) $_GET['business'];
                    if (in_array($biz_id, $branch_ids))
                        $criteria->compare('biz_id', $biz_id);
                    else
                        $criteria->condition = "1=0";
                }

                //set ukey business
                $criteria->compare('biz_id', Users::getIdByUkey($_GET['business']));

                $this->filterBusiness = $_GET['business'];
            }else
            {
                if (!$this->isBranch)
                {
                    $branch_ids = Merchant::getAllBranchByBusiness(Yii::app()->user->id);
                    $criteria->addInCondition('biz_id', $branch_ids);
                }
                else
                {
                    $user       = Yii::app()->user->getCurrentUser();
                    $branch_ids = Merchant::getAllBranchByBusiness($user->author->id);
                    $criteria->addInCondition('biz_id', $branch_ids);
                    //$criteria->compare('biz_id', Yii::app()->user->id);
                }

                $this->filterBusiness = Users::getUkeyById(Yii::app()->user->id);
            }
        }

        if ($this->isStaff)
        {
            $criteria->compare('biz_id', Users::getMyBiz(Yii::app()->user->id));

            $this->filterBusiness = Users::getUkeyById(Users::getMyBiz(Yii::app()->user->id));
        }

        $criteria->order = "user.firstname ASC, user.lastname ASC";
        $model           = Customer::model();
        $count           = $model->count($criteria);
        $pages           = new CPagination($count);
        $pages->route    = $this->route;
        $pages->pageSize = $this->currentLimit;
        $pages->applyLimit($criteria);

        $sort             = new CSort('Customer');
        $sort->attributes = array(
            'user.firstname',
            'biz.business_name',
            'user_id DESC'
        );
        $sort->applyOrder($criteria);

        $data = $model->with('biz', 'user')->findAll($criteria);

        $this->render('index', array(
            'data'  => $data,
            'pages' => $pages,
            'sort'  => $sort,
            'type'  => $this->type
        ));
    }

    private function _history_appointment($model)
    {
        $cri       = new CDbCriteria();
        $cri->compare('t.customer_id', $model->id);
        $cri->with = array('appt');
        if ($this->isBussiness)
        {
            $cri->with = array('appt.service');
            if (!$this->isBranch)
            {
                $branch_ids = Merchant::getAllBranchByBusiness(user()->id);
                $cri->addInCondition('service.author_id', $branch_ids);
            }
            else
                $cri->compare('service.author_id', user()->id);
        }
        elseif ($this->isStaff)
        {
            $cri->compare('appt.author_id', user()->id);
        }
        $cri->order = 'appt.date DESC';
        return AptCustomer::model()->findAll($cri);
    }

    public function _getNotes($model)
    {
        $cri = new CDbCriteria();
        $cri->compare('customer_id', $model->id);
//        if ($this->isAdmin)
//        {
//        }
        if ($this->isBussiness)
        {
            if (!$this->isBranch)
            {
                $branch_ids = Merchant::getAllBranchByBusiness(user()->id);
                $cri->addInCondition('author', $branch_ids);
            }
            else
                $cri->compare('author', user()->id);
        }
        elseif ($this->isStaff)
        {
            $biz_id = Users::getMyBiz(Yii::app()->user->id);
            $cri->compare('author', $biz_id);
        }

        $cri->order      = 't.date DESC';
        $count           = CustomerNote::model()->count($cri);
        $pages           = new CPagination($count);
        $pages->route    = "customer/edit";
        $pages->pageVar  = "notes_page";
        $pages->pageSize = 5;
        $pages->applyLimit($cri);
        $notes           = CustomerNote::model()->findAll($cri);

        $arr_notes = array(
            'notes' => $notes,
            'pages' => $pages);
        return $arr_notes;
    }

    public function actionDelete()
    {
        $this->checkAccess();

// delete record
        if (isset($_GET['pk']))
        {
            $criteria = $this->criteria();
            $criteria->addCondition("ckey='" . trim($_GET['pk']) . "'");
            $customer = Customer::model()->find($criteria);
            if ($customer == NULL)
            {
                throw new CHttpException(404, 'User not found!');
            }
// User ID của Customer bị xóa
            $user_id = $customer->user_id;

// Xóa customer
            $delete = $customer->delete();
            if ($delete)
            {
// Xóa cả thông tin User nếu không còn Customer nào tồn tại dưới tên User này nữa
                $countCustomer = Customer::model()->count('user_id=:u', array(':u' => $user_id));
                if ($countCustomer === 0)
                {
                    CustomerUser::model()->deleteByPk($user_id);
                }
                Yii::app()->user->setFlash('error', 'User deleted!');
            }
            else
            {
                Yii::app()->user->setFlash('error', 'Error, can not delete user, please try again!');
            }
        }
        $this->redirect($this->createUrl(strtolower($this->type) . '/index', @$_GET));
    }

    public function actionView($pk)
    {
        $this->checkAccess();
        $criteria = $this->criteria();
        $criteria->addCondition("ckey='" . trim($pk) . "'");

        $this->customerModel = Customer::model()->find($criteria);

        if ($this->customerModel == null)
            throw new CHttpException(404, Yii::t('yii', 'Customer not found!'));
        if (user()->isMerchant())
        {
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            if (!in_array($this->customerModel->biz_id, $list_branch_ids))
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        }elseif (user()->isBranch())
        {
            $list_branch_ids = Merchant::get_id_all_branch($this->customerModel->biz_id, TRUE);
            if (!in_array(user()->currentUser->author_id, $list_branch_ids))
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        }
        $model = Users::model()->find("id=:u", array(':u' => $this->customerModel->user_id));

        if ($model == null)
            throw new CHttpException(404, Yii::t('yii', 'User not found!'));

        $this->render('//user/view', array(
            'user'     => $model,
            'customer' => TRUE
        ));
    }

    public function actionCreate()
    {
        $this->checkAccess();

        $model = new Customer();

        $model->setScenario("create_backend");
        $this->_form($model, 'create_backend');
    }

    public function actionEdit($pk)
    {
        $this->checkAccess();

        $status_before = '';
        $user          = NULL;

        if (isset($_GET['pk']))
        {
            //find customer
            $customer_model = Customer::model()->find('ckey=:c', array(':c' => $_GET['pk']));
            if ($customer_model == NULL)
            {
                throw new CHttpException(404, Yii::t('yii', 'Customer not found!'));
            }

            $user = $customer_model->user;

            if ($user == NULL)
            {
                throw new CHttpException(404, Yii::t('yii', 'Customer not found!'));
            }
            $status_before = $customer_model->status;
        }
        else
        {
            throw new CHttpException(404, Yii::t('yii', 'Customer not found!'));
        }

        if (user()->isMerchant())
        {
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            if (!in_array($customer_model->biz_id, $list_branch_ids))
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        }elseif (user()->isBranch())
        {
            $list_branch_ids = Merchant::get_id_all_branch($customer_model->biz_id, TRUE);
            if (!in_array(user()->currentUser->author_id, $list_branch_ids))
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        }

        if (isset($_POST['Customer']))
        {

            if (isset($_POST['Customer']['birthday']) AND $_POST['Customer']['birthday'] != '')
            {
                $t              = date_create_from_format("d/M/Y", $_POST['Customer']['birthday']);
                $user->birthday = $t->getTimestamp();
            }

            $user->firstname    = $_POST['Users']['firstname'];
            $user->lastname     = $_POST['Users']['lastname'];
            $user->gender       = $_POST['Users']['gender'];
            $user->occupation   = $_POST['Users']['occupation'];
            $user->address      = $_POST['Users']['address'];
            $user->address2     = $_POST['Users']['address2'];
            $user->city         = $_POST['Users']['city'];
            $user->country      = $_POST['Users']['country'];
            $user->postal_code  = $_POST['Users']['postal_code'];
            $user->home_phone   = $_POST['Users']['home_phone'];
            $user->mobile_phone = $_POST['Users']['mobile_phone'];
            $user->office_phone = $_POST['Users']['office_phone'];
//            $user->author_id=$_POST['Users']['staff_id'];

            if ($user->validate() AND $user->save())
            {
                Yii::app()->user->setFlash('success', 'Save ' . $user->firstname . ' ' . $user->lastname . ' successfully');

                if ($user)
                {
                    $uploadPhoto = $this->_uploadPhoto('user');
                    if ($uploadPhoto)
                    {
                        $user->photo = $uploadPhoto;
                    }
                    $user->update(array('photo'));
                }
            }
        }
        //Customer Notes
        $data_notes      = $this->_getNotes($customer_model);
        $notes           = $data_notes['notes'];
        $note_pages      = $data_notes['pages'];
        //history appointment
        $history_appoint = $this->_history_appointment($customer_model);
        $this->render('form', array(
            'model'           => $customer_model,
            'notes'           => $notes,
            'note_pages'      => $note_pages,
            'history_appoint' => $history_appoint
        ));
    }

    public function _form($model, $action)
    {

//Customer Notes
//        $data_notes = $this->_getNotes($this->customerModel);
//        $notes = $data_notes['notes'];
//        $note_pages = $data_notes['pages'];

        if (isset($_POST['Customer']))
        {
            $post_customer = $_POST['Customer'];

            if (isset($_POST['Users']))
            {
                foreach ($_POST['Users'] as $key => $value)
                    $post_customer[$key] = $value;
            }

            //model customer
            $model->attributes = $post_customer;

            $user_model = Users::check_exist_by_email($_POST['Customer']['email'], Users::TYPE_CUSTOMER);

            if ($user_model)
            {
                $model->user_id        = $user_model->id;
                $user_model->firstname = $model->firstname;
                $user_model->lastname  = $model->lastname;
                $user_model->save();
            }
            else
            {
                //create new user
                $id_user = $this->create_new_user();

                if (!$id_user)
                {
                    Yii::app()->user->setFlash('error', 'Can not creating new user');
                }

                $model->user_id = $id_user;
            }

            if (Yii::app()->user->isAdmin())
            {
                $model->biz_id = $_POST['Users']['biz_id'];
            }

            if (Yii::app()->user->isMerchant())
            {
                $model->biz_id = Yii::app()->user->getId();
            }

            if (Yii::app()->user->isStaff())
            {

                $biz_merchant = Users::getMyBiz(Yii::app()->user->getId());

                if ($biz_merchant)
                {
                    $model->biz_id = $biz_merchant;
                }
            }

            //birthday
            if ($_POST['Users']['birthday'] !== '')
            {
                $bday            = str_replace('/', '-', $_POST['Users']['birthday']);
                $model->birthday = strtotime($bday);
            }

            if ($model->validate() AND $model->save())
            {
                $model->ckey = $model->genCkey();
                $model->update(array('ckey'));
                $biz_ukey    = Users::getUkeyById($model->biz_id);
                Yii::app()->user->setFlash('success', 'Create new customer successfully!');
                $this->redirect($this->createUrl('customer/index', array('business' => $biz_ukey)));
            }
            else
            {
                $html = '';
                $html.='<ul>';

                $error = $model->getErrors();

                foreach ($error as $key => $value)
                {
                    $html.='<li>';
                    $html.=$value[0];
                    $html.='</li>';
                }
                $html.='</ul>';
                Yii::app()->user->setFlash('error', $html);
            }
        }

        $this->render('form', array(
            'model'  => $model,
//            'type' => $model->type,
            'action' => $action,
//            'notes' => $notes,
//            'note_pages' => $note_pages
        ));
    }

    /**
     * return mixed ID of new newuser of <b>FALSE</b> if otherwise
     */
    public function create_new_user()
    {

        $new_user               = new Users();
        $new_user->address      = (isset($_POST['Users']['address'])) ? $_POST['Users']['address'] : "";
        $new_user->status       = $_POST['Customer']['status'];
        $new_user->firstname    = $_POST['Users']['firstname'];
        $new_user->lastname     = $_POST['Users']['lastname'];
        $new_user->city         = (isset($_POST['Users']['city'])) ? $_POST['Users']['city'] : "";
        $new_user->occupation   = (isset($_POST['Users']['occupation'])) ? $_POST['Users']['occupation'] : "";
        $new_user->gender       = $_POST['Users']['gender'];
        $new_user->type         = Users::TYPE_CUSTOMER;
        $new_user->email        = $_POST['Customer']['email'];
        $new_user->country      = (isset($_POST['Users']['country'])) ? $_POST['Users']['country'] : "";
        $new_user->date_created = time();

        $uploadPhoto = $this->_uploadPhoto('user');

        if ($uploadPhoto)
        {
            $new_user->photo = $uploadPhoto;
        }

        if ($this->isAdmin)
        {
            $new_user->author_id = $_POST['Users']['biz_id'];
        }

        if ($this->isBussiness OR $this->isBranch)
        {
            $new_user->author_id = Yii::app()->user->getId();
        }

        if ($new_user->validate() AND $new_user->save())
        {

            //cap nhat ckey
            $new_user->completeCreateUser();

            $new_pass = Utils::genRandomString(6);
            $salt     = $new_user->generateSalt();

            $new_user->salt     = $salt;
            $new_user->password = $new_user->hashPassword($new_pass, $salt);

            $new_user->update(array('salt', 'password'));

            $mail = new MyEmail();

            try
            {
                $mail->sendToNewUser($new_user, $new_pass);
            }
            catch (Exception $exc)
            {
                
            }

            return $new_user->id;
        }
        else
        {
            return FALSE;
        }
    }

    public function saveCustomer($user)
    {
        if (isset($_POST['Customer']))
        {
            $this->customerModel->user_id  = $user->id;
            $this->customerModel->staff_id = $this->staff_id;
            $this->customerModel->biz_id   = $this->biz_id;
            if (isset($_POST['Customer']['birthday']))
            {
                if ($_POST['Customer']['birthday'] != '')
                {
                    $bday                          = str_replace('/', '-', $_POST['Customer']['birthday']);
                    $this->customerModel->birthday = strtotime($bday);
                }
            }
            $isNewRecord = $this->customerModel->isNewRecord;
            if ($this->customerModel->save())
            {
                $this->customerModel->updateCkey();
                if ($isNewRecord)
                {
                    Yii::app()->user->setFlash(
                            'success', 'Created user ' . $this->customerModel->name . ' successfully !'
                    );
                }
                else
                {
                    Yii::app()->user->setFlash(
                            'success', 'Edit user ' . $this->customerModel->name . ' successfully !'
                    );
                }
                $this->redirect('index');
            }
            else
            {
                Yii::app()->user->setFlash('error', 'Can not save customer, please try again!');
            }
        }
    }

    public function save($model)
    {
        $isNewRecord = $model->isNewRecord;
        $auth        = Yii::app()->authManager;

        if ($model->save())
        {
// Sinh va lưu Ukey
            $model->updateUkey();

// Đối với User mới
            if ($isNewRecord)
            {
// Xóa các quyền đã gán trước đây đi
                if ($auth->getAuthAssignments($model->id))
                    foreach ($auth->getAuthAssignments($model->id) as $item)
                        $auth->revoke($item->itemName, $model->id);

// Gán quyền mới vào
                $auth->assign($model->type, $model->id);

// Gửi mail cho user
                $newPwd = $_POST['CustomerUser']['new_pass'];
                $this->_sendMailToNewUser($model, $newPwd);

                Yii::app()->user->setFlash(
                        'success', "Created user $model->name successfully !"
                );
            }
            else
            {
                Yii::app()->user->setFlash(
                        'success', "Edit user $model->name successfully !"
                );
            }

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    public function actionImport()
    {
        $model = new ImportCustomerForm();
        if (Yii::app()->request->isAjaxRequest && $_POST['ajax'] == 'import-form')
        {
            $model->attributes = $_POST['ImportCustomerForm'];
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        $resultArray = array();
        if (isset($_POST['ImportCustomerForm']))
        {

            $model->attributes = $_POST['ImportCustomerForm'];
// Nếu là Staff thì lấy Business ID
            if ($this->isBussiness)
            {
                $model->biz_id = $this->user->id;
            }
            if ($this->isStaff)
            {
                $model->biz_id = $this->user->author_id;
            }

            if (@$_FILES['ImportCustomerForm'])
            {
                $file      = $_FILES['ImportCustomerForm'];
                $tmp_file  = $file['tmp_name']['file'];
                $file_name = $file['name']['file'];

                $import_file = "files/csv/" . md5(time() . $file_name) . "_" . $file_name;
                if (move_uploaded_file($tmp_file, $import_file))
                {
                    $model->file = $import_file;
                }
            }

            if ($model->validate())
            {
                $resultArray = $this->_importCsv($model->file, $model->biz_id, $model->default_password);
                Yii::app()->user->setFlash('success', 'Upload successful!');
            }

            @unlink($model->file);
        }
        $this->render('import', array(
            'model'       => $model,
            'resultArray' => $resultArray
        ));
    }

    public function _importCsv($file, $biz_id, $defaultPass)
    {
        $statusArray = array();
        if (($handle      = fopen($file, "r")) !== FALSE)
        {
            $row  = 0;
            while (($data = fgetcsv($handle, 0, ",")) !== FALSE)
            {
                $row++;
// Bỏ dòng đầu
                if ($row == 1)
                {
                    continue;
                }
                /**
                 * 0: email
                 * 1: FirstName
                 * 2: LastName
                 * 3: Birthday
                 * 4: Gender
                 * 5: Note
                 * 6: Address
                 * 7: City
                 * 8: Country
                 * 9: PostCode
                 * 10: HomePhone
                 * 11: MobilePhone
                 * 12: OfficePhone
                 */
                $email = $data[0];
                $user  = Users::model()->find('email=:e', array(':e' => $email));
                if ($user == null)
                {
                    $user               = new Users();
                    $user->email        = $email;
                    $user->firstname    = $data[1];
                    $user->lastname     = $data[2];
                    $user->birthday     = strtotime($data[3]);
                    $user->gender       = $data[4];
                    $user->note         = $data[5];
                    $user->address      = $data[6];
                    $user->city         = $data[7];
                    $user->country      = $data[8];
                    $user->postal_code  = $data[9];
                    $user->home_phone   = $data[10];
                    $user->mobile_phone = $data[11];
                    $user->office_phone = $data[12];
                    $user->author_id    = $this->user->id;
                    $user->status       = Users::STATUS_ACTIVE;
                    $user->type         = Users::TYPE_CUSTOMER;
                    $user->date_created = time();
                    $user->new_pass     = $defaultPass;

                    if ($user->save())
                    {
                        $user->completeCreateUser();
                        $statusArray[$email] = 'Import successful!';
                    }
                    else
                    {
                        $statusArray[$email] = 'Import fail! Check input content, please!';
                        continue;
                    }
                }

                $customer = Customer::model()->find("user_id=:u AND biz_id=:biz", array(
                    ':u'   => $user->id,
                    ':biz' => $biz_id
                ));

                if ($customer != null)
                {
                    $statusArray[$email] = 'Customer already exist!';
                }
                else
                {
                    $customer               = new Customer();
                    $customer->firstname    = $data[1];
                    $customer->lastname     = $data[2];
                    $customer->birthday     = strtotime($data[3]);
                    $customer->gender       = $data[4];
                    $customer->address      = $data[6];
                    $customer->city         = $data[7];
                    $customer->country      = $data[8];
                    $customer->postal_code  = $data[9];
                    $customer->home_phone   = $data[10];
                    $customer->mobile_phone = $data[11];
                    $customer->office_phone = $data[12];
                    $customer->biz_id       = $biz_id;
                    $customer->user_id      = $user->id;

                    if ($customer->save())
                    {
                        $customer->updateCkey();
                        $statusArray[$email] = 'Import successful!';
                    }
                    else
                    {
                        $statusArray[$email] = 'Import fail! Check input content, please!';
                        continue;
                    }
                }

                unset($user);
                unset($customer);
            }
            fclose($handle);
        }

        return $statusArray;
    }

    public function actionExport()
    {
        $cri = $this->criteria();
        if ($this->isAdmin && isset($_GET['business']) && $_GET['business'] !== 0)
        {
            $biz_id = Users::getIdByUkey($_GET['business']);
            $cri->compare('biz_id', $biz_id);
        }
        if ($this->isBussiness)
        {
            $cri->compare('biz_id', Yii::app()->user->id);
        }
        $cri->order = "t.firstname ASC, t.lastname ASC";
        $customers  = Customer::model()->findAll($cri);
        $fileName   = "CustomersExport_" . @$_GET['key'] . '_' . time() . ".csv";

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");

        $fh     = @fopen('php://output', 'w');
        $header = array(
            'Firstname',
            'LastName',
            'Merchant',
            'Email',
            'Birthday',
            'Gender',
            'Occupation',
            'Area',
            'Address',
            'Address2',
            'City',
            'Country',
            'Post Code',
            'Home phone',
            'Mobile',
            'Office Phone',
            'Notes',
        );
        fputcsv($fh, $header);
        foreach ($customers as $item)
        {
            //lấy note của customer
            $notes   = $this->_getNotes($item);
            $country = Country::getCountrytByCode($item->country);
            $data    = array();
            $data[]  = $item->firstname;
            $data[]  = $item->lastname;
            $data[]  = @$item->biz->name;
            $data[]  = @$item->user->email;
            $data[]  = $item->getBirthday();
            $data[]  = $item->gender;
            $data[]  = @$item->user->occupation;
            $data[]  = $item->city;
            $data[]  = $item->address;
            $data[]  = $item->address2;
            $data[]  = $item->city;
            $data[]  = @$country->name;
            $data[]  = $item->postal_code;
            $data[]  = $item->home_phone;
            $data[]  = $item->mobile_phone;
            $data[]  = $item->office_phone;

            $note_text = '';
            if ($notes['notes'])
            {
                foreach ($notes['notes'] as $val)
                {
                    $note_text .= $val->author_info->type . ': ' . $val->author_info->name . ' | Notes: ' . $val->note_content . ' | Date: ' . $val->formatDate() . "\n";
                }
            }
            $data[] = $note_text;

            fputcsv($fh, $data);
        }
// Close the file
        fclose($fh);
// Make sure nothing else is sent, our file is done
        exit;
    }

    public function actionCreateNote()
    {
        if ($this->isStaff)
        {
            echo 'error';
            Yii::app()->end();
        }
        else
        {
            $biz_id = Yii::app()->user->id;
        }

        $model = new CustomerNote();
        if (isset($_POST['note_content']) && isset($_POST['cus_id']))
        {
            $model->date         = time();
            $model->note_content = $_POST['note_content'];
            $model->author       = $biz_id;
            $model->customer_id  = $_POST['cus_id'];
            if ($model->save())
            {
                $author_link = user()->id == $model->author ? '#' : ($this->isStaff ? '#' : $model->author_info->editUrl);
                $arr         = array(
                    'author_link' => $author_link,
                    'author_img'  => $model->author_info->getAvartBySize(50, 50),
                    'author_name' => $model->author_info->name,
                    'note'        => $model->note_content,
                    'date'        => date('D, F dS, Y', $model->date)
                );
                echo json_encode($arr);
                Yii::app()->end();
            }
            else
            {
                echo 'error';
                Yii::app()->end();
            }
        }
    }

    public function actionUpdateNote()
    {
        $model               = CustomerNote::model()->findByPk($_POST['note_id']);
        $model->note_content = $_POST['note_content'];
        if ($model->save())
        {
            echo 'ok';
            Yii::app()->end();
        }
        else
        {
            echo 'error';
            Yii::app()->end();
        }
    }

    public function actionPackage()
    {
        if (!isset($_GET['pk']))
        {
            throw new CHttpException(404, 'User not found!');
        }
        $this->customerModel = Customer::model()->find("ckey=:i", array(':i' => $_GET['pk']));

        /**
         * phân quyền cho biz chỉ đc nhìn các package của biz
         */
        $cri              = new CDbCriteria();
        $cri->condition   = "customer_id=" . $this->customerModel->id;
        $package_customer = PackageCustomer::model()->findAll($cri);
        if ($package_customer)
        {
            $arr_package_customer = array();
            foreach ($package_customer as $v)
            {
                if ($v->available != 0)
                {
                    $arr_package_customer[] = $v->package_id;
                }
            }
        }

        $cri            = new CDbCriteria();
        $cri->condition = "status=" . Package::STATUS_ACTIVE;
        if ($this->isBussiness)
        {
            $cri->compare('merchant_id', Yii::app()->user->id);
        }
        //Bỏ những package customer đã mua và hết hạn
        if ($package_customer)
        {
            $cri->addNotInCondition('id', $arr_package_customer);
        }
        $count           = Package::model()->count($cri);
        $pages           = new CPagination($count);
        $pages->route    = "customer/package";
        $pages->pageSize = $this->currentLimit;
        $pages->applyLimit($cri);
        $package_model   = Package::model()->findAll($cri);

        $this->render('_package', array(
            'package_customer' => $package_customer,
            'package_model'    => $package_model,
            'pages'            => $pages
        ));
    }

    public function actionAddPackage()
    {
        if (!isset($_GET['p_id']) or ! isset($_GET['pk']))
        {
            throw new CHttpException(404, 'User not found!');
        }
        $pack                = Package::model()->findByPk($_GET['p_id']);
        $this->customerModel = Customer::model()->find("ckey=:i", array(':i' => $_GET['pk']));
        if ($pack && $this->customerModel)
        {
            $model              = new PackageCustomer;
            $model->customer_id = $this->customerModel->id;
            $model->package_id  = $pack->id;
            $model->used_times  = 0;
            $model->available   = $pack->limit;
            if ($model->validate() && $model->save())
            {
                Yii::app()->user->setFlash('success', 'Package Added!');
                Yii::app()->request->redirect(Yii::app()->createUrl('customer/package', array('pk' => $_GET['pk'])));
            }
            else
            {
                $error = $model->getErrors();
                Yii::app()->user->setFlash('error', $error);
                Yii::app()->request->redirect(Yii::app()->createUrl('customer/package', array('pk' => $_GET['pk'])));
            }
        }
    }

}
